package ofpof.domain.dao;

import java.util.Date;

import ofpof.database.MongoDatabaseConnectionProvider;
import ofpof.domain.User;
import ofpof.domain.dao.mapper.UserMapper;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Repository
public class UserDao {

	@Autowired
	private MongoDatabaseConnectionProvider connectionProvider;

	@Autowired
	private UserMapper userMapper;

	public void create(User user) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection userCollection = connection.getCollection("user");
		user.setCreatedOn(new Date());
		user.setId(new ObjectId());
		DBObject dbObject = userMapper.toDbObject(user);
		userCollection.insert(dbObject);
	}

	public User findById(ObjectId userObjectId) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection userCollection = connection.getCollection("user");
		BasicDBObject query = new BasicDBObject("_id", userObjectId);

		DBObject dbObject = (DBObject) userCollection.findOne(query);
		if (dbObject != null) {
			return userMapper.fromDbObject(dbObject);
		}

		return null;
	}

	public User findByEmailAndPassword(String email, String password) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection userCollection = connection.getCollection("user");
		BasicDBObject query = new BasicDBObject("email", email);
		query.put("password", password);

		DBObject dbObject = (DBObject) userCollection.findOne(query);
		if (dbObject != null) {
			return userMapper.fromDbObject(dbObject);
		}
		return null;
	}

	public User findByEmail(String email) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection userCollection = connection.getCollection("user");
		BasicDBObject query = new BasicDBObject("email", email);
		DBObject dbObject = (DBObject) userCollection.findOne(query);
		if (dbObject != null) {
			return userMapper.fromDbObject(dbObject);
		}
		return null;


	}

	public void update(User user) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection userCollection = connection.getCollection("user");
		BasicDBObject query = new BasicDBObject("_id", user.getId());
		
		userCollection.update(query, userMapper.toDbObject(user));
	}
}
